package com.zs.lib_base.utils

import android.text.TextUtils
import java.security.MessageDigest

object Md5Utils {

    fun md5(text: String): String {
        return encryption(text, "MD5")
    }
    fun md5(bytes: ByteArray): String {
        return encryption(bytes, "MD5")
    }

    /**
     * Encryption
     *
     * @param value
     * @param encryptionType the type of encryption
     * @return
     */
    fun encryption(value: String, encryptionType: String): String {
        // 返回值
        var result = ""
        if (TextUtils.isEmpty(value)) {
            return result
        }
        return encryption(value.toByteArray(), encryptionType)
    }


    fun encryption(bytes: ByteArray?, encryptionType: String): String {
        // 返回值
        var result = ""
        if (bytes == null || bytes.isEmpty()) {
            return result
        }
        try {
            // java 加密对象  MessageDigest
            val messageDigest: MessageDigest = MessageDigest.getInstance(encryptionType)
            // 加密字符串
            messageDigest.update(bytes)
            // 转为bytes
            val byteBuffer: ByteArray = messageDigest.digest()
            val stringBuffer = StringBuffer()
            // 遍历加密后字节bytes
            for (i in byteBuffer.indices) {
                val hex = Integer.toHexString(0xFF and byteBuffer[i].toInt())
                if (hex.length == 1) {
                    stringBuffer.append('0')
                }
                stringBuffer.append(hex)
            }
            // 得到返回結果
            result = stringBuffer.toString()
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return result
    }
}